package frame.setup;

import com.ibatis.common.resources.Resources;
import com.ibatis.db.util.ScriptRunner;
import frame.dao.SqlLoader;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * Created by xiaohao on 2014/8/8.
 * 用来初始化数据库的表结构和基本的数据记录
 */
public class SetupUtils {

    private Logger logger = Logger.getLogger(getClass());

    @Autowired
    JdbcTemplate template;

    @Deprecated
    public void init(){

        File file = new File("lock.txt");
        if(!file.exists()){
            //如果锁定文件不存在则进行初始化数据操作
            SqlLoader sqlLoader = new SqlLoader();
            Map<String,String> sqlMap =sqlLoader.getSqlMap();
            Set<String> keys = sqlMap.keySet();
            Iterator<String> iterator =keys.iterator();
            while (iterator.hasNext()){
                String key =iterator.next();
                if(key.startsWith("init")){
                    String sql = sqlMap.get(key);
                    template.execute(sql);
                }

            }
            try{
                file.createNewFile();
            }catch (IOException e){
                e.printStackTrace();
                logger.error("创建锁定文件失败",e);
            }

        }

    }

    /**
     * 利用ibatis-common包的ScriptRunner来初始化数据库脚本
     */
    public void initByIbatis(){
        File file = new File("lock.txt");
        if(!file.exists()) {
            //如果锁定文件不存在则进行初始化数据操作
            Connection conn = null;
            try {
                conn = template.getDataSource().getConnection();
                conn.setAutoCommit(false);
            } catch (SQLException e) {
                e.printStackTrace();
                logger.error("初始化数据获取连接失败",e);
            }
            ScriptRunner scriptRunner = new ScriptRunner();
            scriptRunner.setErrorLogWriter(null);
            scriptRunner.setLogWriter(null);
            scriptRunner.setAutoCommit(false);

            try {
                scriptRunner.runScript(conn, Resources.getResourceAsReader("sql/init.sql"));

            } catch (Exception e) {
                e.printStackTrace();
                logger.error("读取初始化sql文件失败",e);
            }

            try{
                file.createNewFile();
            }catch (Exception e){
                e.printStackTrace();
                logger.error("创建锁定文件失败",e);
            }

        }

    }

}
